#include <iostream>
#include <regex>
// http://admin:password@192.168.1.1/html/index.html?test&bmg
// < scheme >://< user >:< password >@< host >:< port >/< path >;< params >?< query >#< frag >
//一个完整的url包含方案、用户名、密码、主机名、端口、路径、参数、查询和片段
// http://username.password@www.gaia-gis.it:80/gaia-sins/mingw64_ how to.html?key=val&key=val#open-ss
struct URL
{
    std::string protocol;
    std::string username;
    std::string password;
    std::string host;
    int port;
    std::string path;
    std::string params;
    std::string query;
    std::string frag;
};

URL parseURL(std::string urlStr) 
{
    URL url;
    //R:原始字符
    //((\w+):\/\/)? 匹配协议，？表示可选
    //([^\/:]+) 匹配域名
    //(:(\d+))? 匹配端口号
    //(\/.*)?$ 匹配文件路径名 
    //([^?]*)(?:\\?(.*))? $表示必须匹配到字符串结束
    std::regex urlRegex(R"(^((\w+):\/\/)?([^\/:]+)(:(\d+))?([^?]*)(?:\\?(.*))?$)");
    std::smatch urlMatch;
    if (std::regex_match(urlStr, urlMatch, urlRegex)) 
    {
        url.protocol = urlMatch[2];
        url.host = urlMatch[3];
        if (urlMatch[5].matched) 
        {
            url.port = std::stoi(urlMatch[5]);
        }
        else 
        {
            if (url.protocol == "http") {
            url.port = 80;
        }
        else if (url.protocol == "https") 
        {
            url.port = 443;
        }
        }
        if (urlMatch[6].matched) 
        {
            url.path = urlMatch[6];
        }
        else 
        {
            url.path = "/";
        }
        if (urlMatch[7].matched) 
        {
            url.query = urlMatch[7];
        }
        
    }


    return url;
}
int main() {
    std::string urlStr = "http://www.example.com:8080/path?query=param";
    URL url = parseURL(urlStr);
    std::cout << "Protocol: " << url.protocol << std::endl;
    std::cout << "Host: " << url.host << std::endl;
    std::cout << "Port: " << url.port << std::endl;
    std::cout << "Path: " << url.path << std::endl;
    std::cout << "Query: " << url.query << std::endl;
    return 0;
}